package com.quectel.core.module.scheduling.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.parking.ParkingChargingConstants;
import com.quectel.constant.core.scheduling.SchedulingCalendarConfigConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.parking.dto.ParkingChargingSharingTimeDto;
import com.quectel.core.module.scheduling.dao.SchedulingCalendarConfigBindingDao;
import com.quectel.core.module.scheduling.dao.SchedulingCalendarConfigDao;
import com.quectel.core.module.scheduling.dto.SchedulingCalendarConfigBindingDto;
import com.quectel.core.module.scheduling.dto.SchedulingCalendarConfigDto;
import com.quectel.core.module.scheduling.entity.SchedulingCalendarConfigBindingEntity;
import com.quectel.core.module.scheduling.entity.SchedulingCalendarConfigEntity;
import com.quectel.core.module.scheduling.service.SchedulingCalendarConfigBindingService;
import com.quectel.core.module.scheduling.service.SchedulingCalendarConfigService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.DateUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 *
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/07/05 13:24
 */
@DubboService
public class SchedulingCalendarConfigServiceImpl implements SchedulingCalendarConfigService{

    private static final Logger LOGGER = LoggerFactory.getLogger(SchedulingCalendarConfigServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> SCHEDULING_CALENDAR_CONFIG_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "SCHEDULING_CALENDAR_CONFIG_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<SchedulingCalendarConfigDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(SCHEDULING_CALENDAR_CONFIG_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private SchedulingCalendarConfigDao schedulingCalendarConfigDao;
    @Autowired
    private SchedulingCalendarConfigBindingService schedulingCalendarConfigBindingService;
    @Autowired
    private SchedulingCalendarConfigBindingDao schedulingCalendarConfigBindingDao;
    @Autowired
    private VillageService villageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(SchedulingCalendarConfigDto dto) {

        if (dto.getId() == null) {
            Long id = save(dto);
            dto.setId(id);
        } else {
            updateAllColumnById(dto);
        }

        //删除关联关系
        schedulingCalendarConfigBindingDao.delete(new LambdaQueryWrapper<SchedulingCalendarConfigBindingEntity>()
                .eq(SchedulingCalendarConfigBindingEntity::getSchedulingCalendarConfigId, dto.getId())
        );

        // 节假日
        List<String> holidayDates = dto.getHolidayDates();
        if (CollectionUtils.isNotEmpty(holidayDates)){
            for (String date: holidayDates) {
                Date parseDate = DateUtil.parse(date, DateUtils.FormatType.SIMPLE.getType());
                SchedulingCalendarConfigBindingDto addly= new SchedulingCalendarConfigBindingDto();
                addly.setId(Snowflake.nextId());
                addly.setSchedulingCalendarConfigId(dto.getId());
                addly.setType(SchedulingCalendarConfigConstants.DateType.HOLIDAY.getType());
                addly.setDate(parseDate);
                schedulingCalendarConfigBindingService.save(addly);
            }
        }

        List<String> restDates = dto.getRestDates();
        if (CollectionUtils.isNotEmpty(restDates)){
            for (String date: restDates) {
                Date parseDate = DateUtil.parse(date, DateUtils.FormatType.SIMPLE.getType());
                SchedulingCalendarConfigBindingDto addly= new SchedulingCalendarConfigBindingDto();
                addly.setId(Snowflake.nextId());
                addly.setSchedulingCalendarConfigId(dto.getId());
                addly.setType(SchedulingCalendarConfigConstants.DateType.REST.getType());
                addly.setDate(parseDate);
                schedulingCalendarConfigBindingService.save(addly);
            }
        }

    }

    @Override
    public SchedulingCalendarConfigDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                SCHEDULING_CALENDAR_CONFIG_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public SchedulingCalendarConfigDto selectById(Long id){
            SchedulingCalendarConfigEntity entity = schedulingCalendarConfigDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,SchedulingCalendarConfigDto.class));
    }

    @Override
    public List<SchedulingCalendarConfigDto> queryList(Map<String,Object> params){
        List<SchedulingCalendarConfigEntity> list = schedulingCalendarConfigDao.queryList(params);
        List<SchedulingCalendarConfigDto> result =  CopyUtils.copyList(list,SchedulingCalendarConfigDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<SchedulingCalendarConfigDto> queryListWithoutPadding(Map<String,Object> params){
        List<SchedulingCalendarConfigEntity> list = schedulingCalendarConfigDao.queryList(params);
        return CopyUtils.copyList(list,SchedulingCalendarConfigDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private SchedulingCalendarConfigDto paddingField(SchedulingCalendarConfigDto dto){
        if (dto != null){
            if (dto.getVillageId() != null) {
                VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
                if (villageDto != null){
                    dto.setVillageName(villageDto.getName());
                }
            }
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put(LambdaUtil.getFieldName(SchedulingCalendarConfigBindingDto::getSchedulingCalendarConfigId), dto.getId());
            queryMap.put(LambdaUtil.getFieldName(SchedulingCalendarConfigBindingDto::getType), SchedulingCalendarConfigConstants.DateType.HOLIDAY.getType());
            int holidayCount = schedulingCalendarConfigBindingService.queryTotal(queryMap);
            dto.setHolidayCount(holidayCount);

            queryMap.put(LambdaUtil.getFieldName(SchedulingCalendarConfigBindingDto::getType), SchedulingCalendarConfigConstants.DateType.REST.getType());
            int restDayCount = schedulingCalendarConfigBindingService.queryTotal(queryMap);
            dto.setRestDayCount(restDayCount);

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return schedulingCalendarConfigDao.queryTotal(params);
    }

    @Override
    public Long save(SchedulingCalendarConfigDto dto){
        SchedulingCalendarConfigEntity entity = CopyUtils.copyObj(dto,SchedulingCalendarConfigEntity.class);
        entity.setId(Snowflake.nextId());
        schedulingCalendarConfigDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(SchedulingCalendarConfigDto dto){
        SchedulingCalendarConfigEntity entity = CopyUtils.copyObj(dto,SchedulingCalendarConfigEntity.class);

        schedulingCalendarConfigDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(SchedulingCalendarConfigDto dto) {
       SchedulingCalendarConfigEntity entity = CopyUtils.copyObj(dto,SchedulingCalendarConfigEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, schedulingCalendarConfigDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        schedulingCalendarConfigDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            SchedulingCalendarConfigDto schedulingCalendarConfigDto = selectCacheById(id);
            if (schedulingCalendarConfigDto != null) {
                Long[] calendarConfigIds = schedulingCalendarConfigBindingService.selectListByConfigId(schedulingCalendarConfigDto.getId())
                        .parallelStream()
                        .map(SchedulingCalendarConfigBindingDto::getId)
                        .toArray(Long[]::new);
                schedulingCalendarConfigBindingService.deleteBatch(calendarConfigIds);
            }

            deleteById(id);
        }
    }
}
